package com.devframe.web.util.freemarker.directive;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModel;

public class FtlIncResDirective implements TemplateDirectiveModel {
   
    public void execute(Environment env, Map params, TemplateModel[] loopVars,TemplateDirectiveBody body)
            throws TemplateException, IOException {
 
        Writer writer=env.getOut();
        String root="";
		if (env.getDataModel() instanceof TemplateHashModel) {
			TemplateHashModel thm = (TemplateHashModel) env.getDataModel();
			root=thm.get("base").toString();
		}
		String title="";
		Object var=params.get("title");
		if(var!=null){
			title=var.toString();
		}
        String myStr=""
                +"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
                +"<title>"+title+"</title>"
                +"<link rel=\"stylesheet\" type=\"text/css\" href=\""+root+"/css/styleImport.css\" />"
                +"<script type=\"text/javascript\" src=\""+root+"/js/common.js\"></script>";
        
        writer.append(myStr);
        if (body != null) {
            body.render(writer);
            writer.flush();
        } else {
        	body = new IncTemplateDirectiveBody(env);
        }
    }
    
    private static class IncTemplateDirectiveBody implements TemplateDirectiveBody{
    	private Environment env;
    	public IncTemplateDirectiveBody(Environment env){
    		this.env=env;
    	}
    	 public void render(Writer newOut) throws TemplateException, IOException {
             Writer prevOut = env.getOut();
             env.setOut(newOut) ;
             try {
             }finally {
            	 env.setOut(prevOut) ;;
             }
         }
    }
}  